package com.xgx.faceloginback.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.convert.Convert;
import org.apache.commons.codec.binary.Base64;
import com.jfinal.upload.UploadFile;
import com.xgx.faceloginback.common.BaiduAIClient;
import io.jboot.web.controller.JbootController;
import io.jboot.web.controller.annotation.RequestMapping;
import io.jboot.web.cors.EnableCORS;
import org.json.JSONObject;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

@RequestMapping("/upload")

@EnableCORS
public class UploadController extends JbootController {
    public static boolean GenerateImage(String imgStr) { // 对字节数组字符串进行Base64解码并生成图片
        System.out.println(imgStr);
        if (imgStr == null) // 图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
// Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
// 生成jpeg图片
            String imgFilePath = "e:/"+new SimpleDateFormat("yyyyMMddkkmmss").format(new Date())+".png";// 新生成的图片
            File delFile = new File(imgFilePath);
            if(delFile.exists()){
                delFile.delete();
            }

            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    public void image(){

        String sj= getPara("sj");
        BaiduAIClient baiduAIClient=new BaiduAIClient();
        byte[] bytes=Base64.decodeBase64(sj);
        String groupId = "group1";
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("ext_fields", "faceliveness");
        options.put("user_top_num", "3");
        JSONObject res=baiduAIClient.GetAipFaceClient().identifyUser(groupId,bytes,options);
        System.out.println(res.toString(2));
        GenerateImage(sj);
        renderJson(res.toString(2));
    }
    public void uploadImage()  {
        UploadFile upfile = getFile();//JFinal规定getFile()必须最先执行
        File file = upfile.getFile();
        String filename = file.getName();
        String delfilename = filename;
        if(filename!=null && !filename.equals("")){
            filename = new SimpleDateFormat("yyyyMMddkkmmss").format(new Date())+filename;
/**
 * 新保存的位置
 */
            String path = getRequest().getSession().getServletContext()
                    .getRealPath("/");
            String newPath = "/media/file/";//自定义目录  用于存放图片
/**
 * 没有则新建目录
 */
            File floder = new File(path + newPath);
            if (!floder.exists()) {
                floder.mkdirs();
            }
/**
 * 保存新文件
 */
            FileInputStream fis = null;
            FileOutputStream fos = null;
            try{
                File savePath = new File(path + newPath + filename);
                if(!savePath.isDirectory()) savePath.createNewFile();
                fis = new FileInputStream(file);
                fos = new FileOutputStream(savePath);
                byte[] bt = new byte[300];
                while (fis.read(bt, 0, 300) != -1) {
                    fos.write(bt, 0, 300);
                }
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                try{
                    if(null!=fis) fis.close();
                    if(null!=fos) fos.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
/**
 * 删除原图片，JFinal默认上传文件路径为 /upload（自动创建）
 */
            File delFile = new File(path+"/upload/"+delfilename);
            if(delFile.exists()){
                delFile.delete();
            }
            setAttr("msg",filename);
            setAttr("t",1);
        }else{
            setAttr("t",0);
        }
        renderJson("成功！");

    }
}
